<template>
  <div class="user-detail-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <h1>用户详情</h1>
      </div>
      <div class="header-right">
        <el-button @click="editUser">编辑用户</el-button>
        <el-dropdown @command="handleUserAction">
          <el-button type="primary">
            操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="resetPassword">重置密码</el-dropdown-item>
              <el-dropdown-item command="toggleStatus">
                {{ user.status === 'active' ? '禁用用户' : '启用用户' }}
              </el-dropdown-item>
              <el-dropdown-item command="sendMessage">发送消息</el-dropdown-item>
              <el-dropdown-item command="viewLogs" divided>查看日志</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="user-content">
      <el-row :gutter="20">
        <!-- 用户基本信息 -->
        <el-col :span="8">
          <el-card title="基本信息">
            <div class="user-profile">
              <div class="avatar-section">
                <el-avatar :src="user.avatar" :size="80" />
                <div class="user-basic">
                  <h3>{{ user.username }}</h3>
                  <p>{{ user.email }}</p>
                  <el-tag :type="getStatusType(user.status)">
                    {{ getStatusText(user.status) }}
                  </el-tag>
                </div>
              </div>
              
              <div class="user-info">
                <div class="info-item">
                  <span class="label">真实姓名：</span>
                  <span class="value">{{ user.realName || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">手机号码：</span>
                  <span class="value">{{ user.phone || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">用户角色：</span>
                  <span class="value">
                    <el-tag v-for="role in user.roles" :key="role.id" size="small">
                      {{ role.name }}
                    </el-tag>
                  </span>
                </div>
                <div class="info-item">
                  <span class="label">注册时间：</span>
                  <span class="value">{{ formatTime(user.createTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">最后登录：</span>
                  <span class="value">{{ formatTime(user.lastLoginTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">登录IP：</span>
                  <span class="value">{{ user.lastLoginIp || '-' }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 统计信息 -->
        <el-col :span="16">
          <el-card title="统计信息">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.courseCount || 0 }}</div>
                  <div class="stat-label">学习课程</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.taskCount || 0 }}</div>
                  <div class="stat-label">完成任务</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.noteCount || 0 }}</div>
                  <div class="stat-label">学习笔记</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.loginCount || 0 }}</div>
                  <div class="stat-label">登录次数</div>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 活动记录 -->
          <el-card title="最近活动" style="margin-top: 20px">
            <el-timeline>
              <el-timeline-item
                v-for="activity in activities"
                :key="activity.id"
                :timestamp="formatTime(activity.createTime)"
                placement="top"
              >
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-description">{{ activity.description }}</div>
                </div>
              </el-timeline-item>
            </el-timeline>
            <div v-if="activities.length === 0" class="no-activities">
              暂无活动记录
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细信息标签页 -->
      <el-card style="margin-top: 20px">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="学习记录" name="learning">
            <div class="learning-records">
              <el-table :data="learningRecords" v-loading="loadingRecords">
                <el-table-column prop="courseName" label="课程名称" />
                <el-table-column prop="progress" label="学习进度" width="120">
                  <template #default="{ row }">
                    <el-progress :percentage="row.progress" :width="80" />
                  </template>
                </el-table-column>
                <el-table-column prop="lastStudyTime" label="最后学习" width="180">
                  <template #default="{ row }">
                    {{ formatTime(row.lastStudyTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="studyDuration" label="学习时长" width="120" />
                <el-table-column label="操作" width="100">
                  <template #default="{ row }">
                    <el-button size="small" @click="viewCourse(row.courseId)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="任务记录" name="tasks">
            <div class="task-records">
              <el-table :data="taskRecords" v-loading="loadingRecords">
                <el-table-column prop="title" label="任务标题" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getTaskStatusType(row.status)">
                      {{ getTaskStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                  <template #default="{ row }">
                    {{ formatTime(row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="completeTime" label="完成时间" width="180">
                  <template #default="{ row }">
                    {{ row.completeTime ? formatTime(row.completeTime) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="{ row }">
                    <el-button size="small" @click="viewTask(row.id)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="登录日志" name="logs">
            <div class="login-logs">
              <el-table :data="loginLogs" v-loading="loadingRecords">
                <el-table-column prop="loginTime" label="登录时间" width="180">
                  <template #default="{ row }">
                    {{ formatTime(row.loginTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="loginIp" label="登录IP" width="150" />
                <el-table-column prop="userAgent" label="设备信息" />
                <el-table-column prop="location" label="登录地点" width="150" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                      {{ row.status === 'success' ? '成功' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserDetail,
  getUserStats,
  getUserActivities,
  getUserLearningRecords,
  getUserTaskRecords,
  getUserLoginLogs,
  resetUserPassword,
  toggleUserStatus
} from '@/api/user'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const user = ref({})
const userStats = ref({})
const activities = ref([])
const learningRecords = ref([])
const taskRecords = ref([])
const loginLogs = ref([])
const activeTab = ref('learning')
const loadingRecords = ref(false)

// 页面加载
onMounted(async () => {
  await loadUserDetail()
  await loadUserStats()
  await loadActivities()
  await loadTabData()
})

// 加载用户详情
const loadUserDetail = async () => {
  try {
    const response = await getUserDetail(route.params.id)
    if (response.code === 200) {
      user.value = response.data
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 加载用户统计
const loadUserStats = async () => {
  try {
    const response = await getUserStats(route.params.id)
    if (response.code === 200) {
      userStats.value = response.data
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 加载活动记录
const loadActivities = async () => {
  try {
    const response = await getUserActivities(route.params.id)
    if (response.code === 200) {
      activities.value = response.data || []
    }
  } catch (error) {
    console.error('获取活动记录失败:', error)
  }
}

// 加载标签页数据
const loadTabData = async () => {
  loadingRecords.value = true
  try {
    switch (activeTab.value) {
      case 'learning':
        const learningResponse = await getUserLearningRecords(route.params.id)
        if (learningResponse.code === 200) {
          learningRecords.value = learningResponse.data || []
        }
        break
      case 'tasks':
        const taskResponse = await getUserTaskRecords(route.params.id)
        if (taskResponse.code === 200) {
          taskRecords.value = taskResponse.data || []
        }
        break
      case 'logs':
        const logResponse = await getUserLoginLogs(route.params.id)
        if (logResponse.code === 200) {
          loginLogs.value = logResponse.data || []
        }
        break
    }
  } catch (error) {
    console.error('获取记录数据失败:', error)
  } finally {
    loadingRecords.value = false
  }
}

// 标签页切换
const handleTabChange = (tab) => {
  activeTab.value = tab
  loadTabData()
}

// 用户操作处理
const handleUserAction = async (command) => {
  switch (command) {
    case 'resetPassword':
      await resetPassword()
      break
    case 'toggleStatus':
      await toggleStatus()
      break
    case 'sendMessage':
      sendMessage()
      break
    case 'viewLogs':
      activeTab.value = 'logs'
      loadTabData()
      break
  }
}

// 重置密码
const resetPassword = async () => {
  try {
    await ElMessageBox.confirm('确认要重置该用户的密码吗？', '确认重置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await resetUserPassword(user.value.id)
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败')
    }
  }
}

// 切换用户状态
const toggleStatus = async () => {
  try {
    const action = user.value.status === 'active' ? '禁用' : '启用'
    await ElMessageBox.confirm(`确认要${action}该用户吗？`, `确认${action}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await toggleUserStatus(user.value.id)
    user.value.status = user.value.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`用户${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换用户状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 发送消息
const sendMessage = () => {
  router.push(`/message/send?userId=${user.value.id}`)
}

// 编辑用户
const editUser = () => {
  router.push(`/user/edit/${user.value.id}`)
}

// 查看课程
const viewCourse = (courseId) => {
  router.push(`/classroom/course/${courseId}`)
}

// 查看任务
const viewTask = (taskId) => {
  router.push(`/task/detail/${taskId}`)
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'active': 'success',
    'inactive': 'danger',
    'pending': 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'active': '正常',
    'inactive': '禁用',
    'pending': '待激活'
  }
  return textMap[status] || '未知'
}

// 获取任务状态类型
const getTaskStatusType = (status) => {
  const typeMap = {
    'completed': 'success',
    'in_progress': 'warning',
    'pending': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取任务状态文本
const getTaskStatusText = (status) => {
  const textMap = {
    'completed': '已完成',
    'in_progress': '进行中',
    'pending': '待开始',
    'cancelled': '已取消'
  }
  return textMap[status] || '未知'
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.user-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.user-profile {
  .avatar-section {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;
    
    .user-basic {
      h3 {
        margin: 0 0 8px 0;
        font-size: 18px;
        color: #303133;
      }
      
      p {
        margin: 0 0 8px 0;
        color: #606266;
      }
    }
  }
  
  .user-info {
    .info-item {
      display: flex;
      margin-bottom: 12px;
      
      .label {
        width: 80px;
        color: #606266;
        font-size: 14px;
      }
      
      .value {
        flex: 1;
        color: #303133;
        font-size: 14px;
      }
    }
  }
}

.stat-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  
  .stat-number {
    font-size: 24px;
    font-weight: 600;
    color: #409eff;
    margin-bottom: 8px;
  }
  
  .stat-label {
    color: #606266;
    font-size: 14px;
  }
}

.activity-content {
  .activity-title {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .activity-description {
    color: #606266;
    font-size: 14px;
  }
}

.no-activities {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
  }
  
  .info-item {
    flex-direction: column;
    
    .label {
      width: auto;
      margin-bottom: 4px;
    }
  }
}
</style>
